/*
 * @Author: song
 * @Description: 声音轨道绘制
 * @Date: 2024年04月28日 星期日 20:04:04
 * @Modify:
 */

using Function.SkillEditor.Runtime;
using SCore.Editor.WindowDraw;
using SCore.Function.Fixed;
using SCore.Editor;
using UnityEditor;
using UnityEngine;

namespace Function.SkillEditor.Editor
{
    public class SkillAudioClipDraw : ISkillClipDrawer
    {
        public override void OnInspector(Rect rect)
        {
            base.OnInspector(rect);
            EditorGUI.BeginChangeCheck();
            var audioClip =
                EditorDrawHelp.DrawHObjetField(new Rect(rect.x, GetInspectorHeight(rect), rect.width, 20),
                    "Object", _skillClip._asset as AudioClip);
            if (EditorGUI.EndChangeCheck())
            {
                _skillClip._asset = audioClip;
            }
        }

        public override void OnEnter(fp progress)
        {
            // 从当前帧开始播放
            fp eventTimeInSeconds =
                progress - _skillClip._startFrame * SkillRunMap.Instance.GetEOneFrameTime();
            int sampleRate = ((AudioClip)_skillClip._asset).frequency;
            int sample = (int)(sampleRate * eventTimeInSeconds.AsFloat());
            EditorAudioUtil.PlayPreviewClip(((AudioClip)_skillClip._asset), sample, false);
        }

        public override void OnExit(bool isPlay, fp progress)
        {
            EditorAudioUtil.StopPreviewClip((AudioClip)_skillClip._asset);
        }

        public override void OnDisable()
        {
            EditorAudioUtil.StopPreviewClip((AudioClip)_skillClip._asset);
        }
    }


    [TrackDrawEditor(typeof(SkillAudioTrack), typeof(SkillAudioClipDraw))]
    public class SkillAudioTrackDraw : ISkillTrackDrawer<SkillAudioTrack>
    {
        public SkillAudioTrackDraw(SkillAudioTrack skillTrack, TrackRegisterAttribute trackRegister) : base(skillTrack,
            trackRegister)
        {
        }

        protected override void DrawGroup()
        {
            EditorGUI.LabelField(new Rect(_headRect.x + 10, _headRect.y, _headRect.width, _headRect.height), "Audio");
        }

        protected override void OnTimeLinePlayStatusChange(bool play)
        {
            if (!play)
            {
                EditorAudioUtil.StopAllPreviewClips();
            }

            base.OnTimeLinePlayStatusChange(play);
        }
    }
}